package cn.com.zetatech.loader.util;
import jcifs.CIFSContext;
import jcifs.CIFSException;
import jcifs.config.PropertyConfiguration;
import jcifs.context.BaseContext;
import jcifs.smb.NtlmPasswordAuthenticator;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

public class NASUploadUtils {

    /**
     * 上传BufferedImage到NAS服务器
     *
     * @param bufferedImage BufferedImage对象
     * @param nasUrl        NAS服务器上的共享文件夹URL（包含文件名）
     * @param username      用户名
     * @param password      密码
     * @throws IOException 如果发生IO错误
     */
    public static void uploadImageToNAS(BufferedImage bufferedImage, String nasUrl, String username, String password) throws IOException {
        // 配置鉴权信息
        Properties prop = new Properties();
        prop.put("jcifs.smb.client.dfs.disabled", "true");
        CIFSContext baseContext = new BaseContext(new PropertyConfiguration(prop));
        CIFSContext authContext = baseContext.withCredentials(new NtlmPasswordAuthenticator(username, password));

        // 创建SmbFile对象
        SmbFile smbFile = new SmbFile(nasUrl, authContext);

        // 检查目标文件夹是否存在，如果不存在则创建
        SmbFile parentDir = new SmbFile(smbFile.getParent(), authContext);
        if (!parentDir.exists()) {
            parentDir.mkdirs(); // 递归创建所有不存在的父文件夹
        }

        // 将BufferedImage转换为字节数组输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", baos);
        byte[] imageBytes = baos.toByteArray();

        // 上传文件到NAS
        try (SmbFileOutputStream sfos = new SmbFileOutputStream(smbFile)) {
            sfos.write(imageBytes);
            sfos.flush();
        } catch (CIFSException e) {
            throw new IOException("Failed to upload image to NAS", e);
        }
    }


    public static void main(String[] args) {
        try {
            // 示例：上传图像到NAS
            BufferedImage image = ImageIO.read(new File("/Users/hechangyu/all/loader-parent/wafer_with_dies.png"));
            String nasUrl = "smb://10.10.100.90/zeta-ays/Y/接口文档/uploaded_image.png";
            String username = "zeta.ays";
            String password = "zeta@ays#2023";

            uploadImageToNAS(image, nasUrl, username, password);
            System.out.println("Image uploaded successfully to NAS.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

